如何使用NodeJS模块等待?
我有下面的代码,使用技术上工作(我认为 )的await模块。
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
一切似乎都应该履行承诺。 但是,它看起来像在同步执行而不是asynchronous执行。 我会期待看到:
start IN FUNCTION one IN FUNCTION two DONE WIH FUNCTION one DONE WIH FUNCTION two end got data for one got data for two
这也需要大约10秒,它应该只需要5秒钟大麦。
睡眠是阻塞的,而不是将控制返回到事件循环,所以你的代码只是在睡觉的地方睡觉。
如果你把它转换为asynchronous,像这样的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
这对我来说是正确的。