亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使函數等到使用node.js調用回調

如何使函數等到使用node.js調用回調

GCT1015 2019-07-29 15:27:19
如何使函數等到使用node.js調用回調我有一個簡化的功能,如下所示:function(query) {   myApi.exec('SomeCommand', function(response) {     return response;   });}基本上我希望它調用myApi.exec,并返回回調lambda中給出的響應。但是,上面的代碼不起作用,只是立即返回。只是為了一個非常hackish嘗試,我嘗試了下面沒有工作,但至少你明白了我想要實現的目標:function(query) {   var r;   myApi.exec('SomeCommand', function(response) {     r = response;   });   while (!r) {}   return r;}基本上,什么是一個好的'node.js /事件驅動'的方式來解決這個問題?我希望我的函數等到調用回調,然后返回傳遞給它的值。
查看完整描述

3 回答

?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

“good node.js / event driven”這樣做的方法就是不要等待

與使用像節點這樣的事件驅動系統幾乎所有其他內容一樣,您的函數應該接受一個回調參數,該參數將在計算完成時調用。調用者不應該等待正常意義上的“返回”值,而是發送將處理結果值的例程:

function(query, callback) {
  myApi.exec('SomeCommand', function(response) {
    // other stuff here...
    // bla bla..
    callback(response); // this will "return" your value to the original caller
  });}

所以你不要這樣使用它:

var returnValue = myFunction(query);

但是像這樣:

myFunction(query, function(returnValue) {
  // use the return value here instead of like a regular (non-evented) return value});


查看完整回答
反對 回復 2019-07-29
?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

實現此目的的一種方法是將API調用包裝到promise中,然后使用await等待結果。

// let's say this is the API function with two callbacks,// one for success and the other for errorfunction apiFunction(query, successCallback, errorCallback) {
    if (query == "bad query") {
        errorCallback("problem with the query");
    }
    successCallback("Your query was <" + query + ">");}// myFunction wraps the above API call into a Promise// and handles the callbacks with resolve and rejectfunction apiFunctionWrapper(query) {
    return new Promise((resolve, reject) => {
        apiFunction(query,(successResponse) => {
            resolve(successResponse);
        }, (errorResponse) => {
            reject(errorResponse)
        });
    });}// now you can use await to get the result from the wrapped api function// and you can use standard try-catch to handle the errorsasync function businessLogic() {
    try {
        const result = await apiFunctionWrapper("query all users");
        console.log(result);

        // the next line will fail
        const result2 = await apiFunctionWrapper("bad query");
    } catch(error) {
        console.error("ERROR:" + error);
    }}// call the main functionbusinessLogic();

輸出:

Your query was <query all users>ERROR:problem with the query


查看完整回答
反對 回復 2019-07-29
  • 3 回答
  • 0 關注
  • 535 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號