0

我正在尝试在我的 node.js 微服务中使用 Promise.all。Promise.all 的目的是遍历(查询)数组中的所有元素,并通过 apolloFetch 调用另一个微服务,然后在数据库中执行这些查询,然后返回成功或错误。我收到一个“包装的承诺不可迭代”错误——我检查了一些关于 SO 的帖子,它们有类似的错误,但在所有这些情况下,都传递了 2 个参数,而我只传递了一个——除了我是使用 apolloFetch 连接到另一个 MICROSERVICE,该 MICROSERVICE 接受每个查询(在数组中),然后对数据库执行一些操作。

有人可以弄清楚我在这里做错了什么:

     const QryAllBooks = {
    type: new GraphQLList(BookType),
    args: {},
    resolve(){
          return new Promise((resolve, reject) => {
             let sql = singleLineString`
                  select distinct t.bookid,t.bookname,t.country
                  from books_tbl t
                  where t.ship_status = 'Not Shipped'
              `;
             pool.query(sql, (err, results) => {
               if(err){
                  reject(err);
               }
               resolve(results);

            const str = JSON.stringify(results);
            const json = JSON.parse(str);

            const promises = [];
            for (let p = 0; p < results.length; p++){
               const book_id = json[p].bookid;
               const query = `mutation updateShipping
                              {updateShipping
                               (id: ${book_id}, input:{
                                  status: "Shipped"
                               })
                               { bookid
                                 bookname }}`
                promises.push( query );
           }

          //I need an await function so that previous apolloFetch  
          //goes in sequence of bookid, one after the other

          Promise.all( promises.map(p=>apolloFetch({p})) ).then((result) => 
         {
                  resolve();
                  console.log("success!");
                  })
                 .catch(( e ) => {
                     FunctionLogError( 29, 'Error', e );
                 )};
                  });
            });
        }
      };

   module.exports = {
          QryAllBooks,
          BookType
   };
4

1 回答 1

1

代码从调用中获取返回值apolloFetch,并无条件地将其提供给Promise.all.

我认为答案是:

有人可以弄清楚我在这里做错了什么

是,您不允许apolloFetch返回与可迭代集合不同的东西的情况。

相反,调用apolloFetch,判断返回值是否是可迭代的并且只有它是可迭代的时,才调用Promise.all.

如果apolloFetch返回的不是可迭代的,你需要决定你的代码应该如何表现。目前它引发了一个错误,这显然不是你想要的;但你需要决定在这种情况下你想要什么。

于 2019-02-27T03:12:39.090 回答