简体   繁体   English

如何在内部 promise 解析后让我的外部 function 返回?

[英]How do I make my outer function return after the inner promise resolves?

I'm using the Google Sheets API to get some data, and I'm having trouble with the syntax for getting the outer function to return only after the inner function's promise has resolved.我正在使用 Google 表格 API 来获取一些数据,我在使用语法时遇到了问题,因为只有在内部函数的 promise 已解析后,才能让外部 function 返回。

I need getData() to return only after the promise has resolved我需要 getData() 仅在 promise 已解决后返回

async function getData(auth) {
    console.log("GET DATA RAN");
    let sheet = sheetIDGlobal;
    let selectedRow = sheetsRow;
    const sheets = await google.sheets({ version: 'v4', auth });
    console.log("Waiting for Google Sheets reply .....");

    const rowGetter = await sheets.spreadsheets.values.get({
        spreadsheetId: sheet,
        range: selectedRow,
    }, (err, res) => {
        if (err) return console.log('The API returned an error: ' + err);
        const rows = res.data.values;
        if (rows.length) {
            // console.log(rows, "<----- ROWS");
            promises = rows.forEach((row) => {
                section = `${row[0]}`
                // just saving some variables here
            })
            function runIfFirst() {
                if (tracker === 0) {
                    fillDataPropType(auth)
                }
            }
            Promise.resolve(promises).then(runIfFirst());
        } else {
            console.log('No data found.');
        }
    })
    // trying to get the outer function to return after the inner function is complete.
    return await rowGetter;
}

I tried assigning the inner function to a variable and awaiting the reply for that variable to be returned but I don't understand what I need to do to have the outer function wait on the inner function.我尝试将内部 function 分配给一个变量并等待返回该变量的回复,但我不明白我需要做什么才能让外部 function 等待内部 function。

It seems that the issue is that in this part, you are mixing a callback and a promise.似乎问题在于,在这部分中,您混合了回调和 promise。

const rowGetter = await sheets.spreadsheets.values.get({
  spreadsheetId: sheet,
  range: selectedRow,
}, (err, res) => { /* ... */ })

I suppose the spreadsheets API supports both.我想电子表格 API 都支持。 Using await here means you expect it returns a promise, so you shouldn't pass a callback function to the second argument.在这里使用await意味着您期望它返回 promise,因此您不应将回调 function 传递给第二个参数。 If you want to use a callback, then no await is required.如果您想使用回调,则不需要await It won't return anything either.它也不会返回任何东西。 You only need to choose one.你只需要选择一个。

I think promise + await is probably easier to understand:我认为 promise + await 可能更容易理解:

const res = await sheets.spreadsheets.values.get({
  spreadsheetId: sheet,
  range: selectedRow,
})
const rows = res.data.values;
if (rows.length) {
  // omitted...
}
// omitted...
return rowGetter;

I'm not sure what is the rowGetter , but you just need to remove the callback argument and move those code outside.我不确定rowGetter是什么,但您只需要删除回调参数并将这些代码移到外面。

Or, if you decided to use the callback, but still want the getData() to return a promise, then you need to convert it to a promise yourself.或者,如果您决定使用回调,但仍希望getData()返回 promise,那么您需要自己将其转换为 promise。 For example:例如:

return new Promise((resolve, reject) => {
  sheets.spreadsheets.values.get({
    spreadsheetId: sheet,
    range: selectedRow,
  }, (err, res) => {
    if (err) {
      reject(err);
      return console.log('The API returned an error: ' + err);
    }
    const rows = res.data.values;
    // omitted ...
    resolve(rowGetter);
  });  
});

In this case, you don't await sheets.spreadsheets.values.get and it won't return anything.在这种情况下,您无需等待sheets.spreadsheets.values.get并且它不会返回任何内容。 Because the return value is the res in the callback function.因为返回值是回调function中的res

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建一个函数,返回一个在内部承诺解决后解决的承诺 - How to create a function returning a promise that resolves after inner promise resolves 纯函数可以返回一个随机时间后解析的承诺吗? - Can a pure function return a promise that resolves after a random amount of time? 如何将一个诺言中的值返回给我的调用函数? - How do I return a value from a promise to my calling function? 当事件发射器在JS或Node JS中发出事件时,如何做出可解决的Promise? - How do I make a Promise that resolves when an event emitter emits an event in JS or Node JS? 如何使用 Jest 解析模拟函数中的外部承诺? - How do I resolve the outer promise inside a mocked function with Jest? 有没有办法保证Promise.all在一个内部允诺的“ then”链之后解决? - Is there a way to guarantee `Promise.all` resolves after the `then` chain of an inner promise? 潜在的异步函数会返回一个立即解析的承诺吗? - Potentially async function return a promise that immediately resolves? 如何创建一个解析为一个版本的javascript承诺? - How do I create a javascript promise which resolves to a thenable? 承诺解决后从函数返回结果 - Returning a result from a function after a promise resolves 我如何使这个功能成为现实? - How do I make this function a promise?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM