我有一个代码,等待文件存在并返回文件内容。我运行代码,它等待'smscode.txt'文件。我上传“ smscode.txt”代码后,执行完成。没错。
但是出于某种原因console.log(2);什么都不显示。 这是我执行函数的结果。
c:\work\docker\test-npm>node ideaOpen.js
1
c:\work\docker\test-npm>
更新和简化的代码版本,没有文件
我希望显示“ 2”,但不会显示。在5秒钟内脚本成功完成了工作。
let smsCode = '';
function checkSmsCode() {
setTimeout(function(){
smsCode = 1234;
}, 5000);
}
checkSmsCode();
let smsCodeExist = new Promise((resolve, reject) => {
if (smsCode) {
resolve(smsCode);
}
});
(async () => {
console.log(1);
let a = await smsCodeExist;
console.log(2);
})();
答案 0 :(得分:0)
借助这个stackoverflow问题,我找到了一个解决方案。 Use Promise to wait until polled condition is satisfied
let smsCode = '';
function checkSmsCode() {
setTimeout(function(){
smsCode = 1234;
}, 5000);
}
checkSmsCode();
let smsCodeExist = new Promise(function (resolve, reject) {
waitForSmsCode(resolve);
});
function waitForSmsCode(resolve) {
if (!smsCode) {
setTimeout(waitForSmsCode.bind(this, resolve), 500);
} else {
resolve(smsCode);
}
}
(async () => {
console.log(1);
let a = await smsCodeExist;
console.log(2);
console.log(a);
})();
P.S。 读取文件时回答原始问题(脚本等到文件存在)
var fs = require('fs');
let smsCode = '';
function waitForSmsCode(resolve) {
fs.readFile('smscode.txt', 'utf8', (err, contents) => {
smsCode = contents;
});
if (!smsCode) {
setTimeout(waitForSmsCode.bind(this, resolve), 500);
} else {
resolve(smsCode);
}
}
let smsCodeExist = new Promise((resolve, reject) => {
waitForSmsCode(resolve);
});
(async () => {
console.log(1);
let smsCode = await smsCodeExist;
console.log(smsCode);
})();