我有以下代码使用技术上有效的await模块(我认为)。
var statement1 = "";
$scope.DiamoniImagesArray1 = [];
db.transaction(function (tx) {
statement1 = "UPDATE objects SET Favorites='1' where objectid='126'";
tx.executeSql(statement1, [], function (tx, res) {
alert("change");
}, function (e) {
alert("Something went wrong");
});
}, function (e) {
alert('transaction error: ' + e.message);
});
输出结果为:
var await = require('await')
var sleep = require('sleep')
var things = await('one', 'two');
function getData(key){
console.log("IN FUNCTION " + key);
sleep.sleep(5);
var data = "got data for " + key;
things.keep(key, data);
console.log("DONE WIH FUNCTION " + key);
}
console.log("start");
getData('one');
getData('two');
console.log('end');
things.then(function(got){
console.log(got.one);
console.log(got.two);
}
);
一切似乎都得到了传承,因为它应该履行承诺。但是,看起来它是异步执行而不是异步执行。我原本希望看到:
start
IN FUNCTION one
DONE WIH FUNCTION one
IN FUNCTION two
DONE WIH FUNCTION two
end
got data for one
got data for two
它也需要大约10秒钟,它应该只需要大麦超过5秒。
答案 0 :(得分:1)
睡眠是阻塞的,并且没有将控制权返回给事件循环,所以你的代码只是在它睡觉的地方睡觉。
如果您将其转换为异步,请使用setTimeout
,如下所示:
function getData(key){
console.log("IN FUNCTION " + key);
setTimeout(function() {
var data = "got data for " + key;
things.keep(key, data);
console.log("DONE WIH FUNCTION " + key);
}, 5000);
}
我得到了这个输出:
start
IN FUNCTION one
IN FUNCTION two
end
DONE WIH FUNCTION one
got data for one
got data for two
DONE WIH FUNCTION two
对我而言看起来是正确的。