简体   繁体   English

如何避免嵌套承诺?

[英]How to Avoid nesting promises?

How could I modify the following code to avoid nesting Promises?如何修改以下代码以避免嵌套承诺?

The response of request-promise is needed to be inserted in Firestore.需要在 Firestore 中插入 request-promise 的响应。

I would also like to know how to have the jsonresponse available when the Firestore Promise is resolved to send the response.status to the caller aplication.我还想知道当 Firestore Promise 被解析为将 response.status 发送给调用方应用程序时如何使 jsonresponse 可用。

const functions = require('firebase-functions');
const rp = require('request-promise')
var admin = require("firebase-admin");

var serviceAccount = require("./service_key.json");

admin.initializeApp({
   credential: admin.credential.cert(serviceAccount),
   databaseURL: "https://melitest-5bc38.firebaseio.com"
});

let db = admin.firestore()

exports.customHttpRequest = functions.https.onRequest((request, response) => { 

const url = 'https://jsonplaceholder.typicode.com/users'

var options = {
    uri: url,
    method: "GET",
    json: true
};

rp(options).then((jsonresponse) => {
     for(var i = 0 ; i < jsonresponse.length; i++){
        var obj = jsonresponse[i]
        var docid = obj.id

        // Warning: Avoid nesting promises.eslint(promise/no-nesting)
        db.collection("scrapeusertest").doc(String(docid)).set(obj).then(() =>{ 
            console.log(`Data was upload to firestore and the response was: ${jsonresponse}`)
            response.status(200).send(jsonresponse);
        }).catch(error =>{
            console.log(`Error uploading data Firebase: ${error}`)
        });

    }
    return console.log("Data was send")
})
.catch((err) => {
    console.log('Error:', err)

});
    return null;
});

Easiest option is to use an async function:最简单的选择是使用异步函数:

const db = admin.firestore()

exports.customHttpRequest = functions.https.onRequest(async (request, response) => { 

  const url = 'https://jsonplaceholder.typicode.com/users'
  const options = {
    uri: url,
    method: "GET",
    json: true
  };

  const jsonresponse = await rp(options);

  await Promise.all(jsonresponse.map(async obj => {
    const docid = obj.id
    try {
      await db.collection("scrapeusertest").doc(String(docid)).set(obj);
    } catch (error) {
      console.log(`Error uploading data Firebase: ${error}`);
    }
  }));

  console.log(`Data was upload to firestore and the response was: ${jsonresponse}`);
  response.status(200).send(jsonresponse);
});

use promise and used the promise all as this shape使用承诺并将承诺全部用作此形状

    const res= await rp(options);
//should be soure the res is array
     await Promise.all(res.map( async item =>{
    const id=item.id;
     try {
          await db.collection("scrapeusertest").doc(String(id)).set(item);
        } catch (error) {
    //what action when handle wrror
        }))})

you can use the res as what you need您可以根据需要使用资源

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM