[英]How do I wait for the API response in Node JS before executing next line
我在 node.js 中撥打 get API 需要等待響應。 回復 Alexa Skill 的 output。
const GetReportOnEmail = function (UserID, ReportName) {
return new Promise(function(resolve, reject){
var options = {
uri:'https://www.xxxxx/xx/xx',
method : 'GET'
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res = body;
resolve(res);
}
else {
res = 'Not Found';
reject(res);
}
});
})
} module.exports.GetReportOnEmail=GetReportOnEmail;
這個function我是在另一個js文件中調用的:
setTimeout(function () {
GetReportEmail.GetReportOnEmail('userID', 'ReportName').then((resp) => {
speechText = resp;
}).catch((error) => {
speechText = "some error occurred";
})
}, 20000);
-----更多代碼行--------
在執行下一行代碼之前,我需要等待這個 API 的響應。 我怎么做。 問候,納文
我會使用異步/等待。
如果您在立即調用的async
function 中運行整個主程序,則可以將await
放在返回Promise
的任何 function 之前。
任何一個:
async function mainProgram() {
// do stuff
}
mainProgram();
只是
(async function () {
// do stuff
})()
你需要一個返回 promise 的sleep
function。我通常只做一個這樣的:(但我確信也有地方可以導入一個)
function sleep(t) {
return new Promise(function(resolve) {
setTimeout(resolve, t);
});
};
然后 go 這樣:
(async function() {
await sleep(20000);
const speechText = await GetReportEmail.GetReportOnEmail(
'userID',
'ReportName',
).catch((error) => {
return "some error occurred";
})
console.log(speechText);
});
上面的混合和匹配 then/catch 和 async/await。 你也可以這樣做:
(async function() {
await sleep(20000);
let speechText;
try {
speechText = await GetReportEmail.GetReportOnEmail(
'userID',
'ReportName',
)
} catch (e) {
speechText = "some error occurred";
}
console.log(speechText);
});
如果你不想使用異步等待
setTimeout(function () {
GetReportEmail.GetReportOnEmail(
'userID',
'ReportName',
).catch((error) => {
return "some error occurred";
}).then(function(resp) {
const speechText = resp;
// do something like
console.log(speechText);
});
}, 20000);
把你想做的事情放到then
中。
原來你設置了一個每個人都可以使用的speechTex
t 變量,但在這里我只是將值傳遞給下一個 then。 所以我擺脫了你擁有的then
,它只會傳遞它收到的相同價值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.