簡體   English   中英

如何在 Node.js 中等待回調 function 調用?

[英]How to await a callback function call in Node.js?

我是 Node.js 和 Javascript 的新手,我使用了 npm ZEFE90A8E604A7C840E88D03A677 重試發送請求到服務器。

const retry = require('retry');

async function HandleReq() {

//Some code
return await SendReqToServer();
}

async function SendReqToServer() {
 
operation.attempt(async (currentAttempt) =>{
        try {
            let resp = await axios.post("http://localhost:5000/api/", data, options);
            return resp.data;
        } catch (e) {
            if(operation.retry(e)) {throw e;}
        }
    });
}

我收到空響應,因為SendReqToServer在 function 傳遞給operation.attempt之前返回 promise。嘗試解析 promise。

如何解決這個問題?

這個問題的解決方案取決於operation.attempt 如果它返回 promise 您也可以在SendReqToServer中簡單地返回 promise 。 但通常帶有回調的異步函數不會返回承諾。 創建您自己的 promise:

const retry = require('retry');

async function HandleReq() {

//Some code
return await SendReqToServer();
}

async function SendReqToServer() {
 
    return new Promise((resolve, reject) => {
        operation.attempt(async (currentAttempt) => {
            try {
                let resp = await axios.post("http://localhost:5000/api/", data, options);
                resolve(resp.data);
                return resp.data;
            } catch (e) {
                if(operation.retry(e)) {throw e;}
            }
        });
    });
}

如果 function 中沒有錯誤,則返回operation.attempt()將返回resp.datasendReqToServer() 目前,您只是將resp.data返回給operation.attempt() 您還需要返回operation.attempt()

const retry = require('retry');

async function HandleReq() {

//Some code
return SendReqToServer();
}

async function SendReqToServer() {
 
return operation.attempt(async (currentAttempt) => {
        try {
            let resp = await axios.post("http://localhost:5000/api/", data, options);
            return resp.data;
        } catch (e) {
            if(operation.retry(e)) {throw e;}
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM