Node.JScallback里面while
我想做的事:
var found = false; while (!found){ var result = db.getNextRecord(); if (result == search_term){ return result; } }
问题是,getNextRecord是asynchronous的
var nothing_returned = db.getNextRecord(function(err, result){ // I have the result in this callback, but not before });
鉴于getNextRecord(cb)的行为,我如何重写上面的代码片段来获得相同的结果?
既然你有一个async
函数,你想同步调用,你有两个select。 如果有一个可用的方法,使用sync
版本的方法,但如果没有,那么你将不得不改变你的逻辑。
以下片段应该做你想做的,它需要asynchronous库。
var async = require('async'); var result; async.whilst( function () { return !result; }, function (callback) { db.getNextRecord(function (err, record) { if (err) { return callback(err); } if (result == search_term) { result = record; } return callback(); }); }, function (err) { // Search is complete, do what you wish with result in this function. This function // will be called when whilst is done or if getNextRecord got an error. } );
我敢肯定,如果你想更改逻辑,有一个更简单的方法来做到这一点,但这是类似的做一段while
但asynchronous。
使用asynchronous库。 它的function看起来像你所需要的: https : //www.npmjs.com/package/async#until
var async = require('async'); var latestResult = null; async.until(function () { return latestResult == search_term; }, function () { db.getNextRecord(function (err, result) { latestResult = result; }); }, function () { // now you can do something with latestResult });
您还应该考虑在应用程序中执行此操作是否合理,或让数据库查询包含此过滤。
随着babel
和新JS:
import {promisify as pr} from 'es6-promisify'; async function find(search_term) { let found = false, result=null; while (!found){ let result = await pr(db.getNextRecord)(); if (result == search_term){ found=true; } } return result; }