为什么我的apolloFetch调用在promise.all中调用时返回一个空查询?[英] Why is my apolloFetch call returning an empty query when called from within a promise.all?

本文是小编为大家收集整理的关于为什么我的apolloFetch调用在promise.all中调用时返回一个空查询?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在尝试在我的node.js microservice中使用apolloFetch apolloFetch,但请继续遇到查询是空的错误.使用apolloFetch的原因是调用另一个微服务并将其传递到一系列查询.有人可以给我一些指导吗?我的代码如下:

   const uri = "dsc.xxx.yyyy.com/abc/def/graphql";
   const apolloFetch = CreateApolloFetch({uri});
  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);
                }
                //Below is the Promise.all function with the   
                //apolloFetch that calls another graphql endpoint
                //an array of queries
                Promise.all(promises.map(p => apolloFetch({p}))).then((result) => {
                    //this is the problem code^^^^^^^^^^^^^^^^^^^^^ 
                    resolve();
                    console.log("success!");
                }).catch((e) => {
                    FunctionLogError(29, "Error", e);
                });
            });
        });
    }
};
module.exports = {
    QryAllBooks,
    BookType
};

推荐答案

看起来Apollofetch需要query - 您正在通过p

更改

Promise.all( promises.map(p=>apolloFetch({p})) )

to

Promise.all( promises.map(query=>apolloFetch({query})) )

您还会致电两次

解决所有错误或成功

const final_results = []
Promise.all(promises.map(query => apolloFetch({
  query,
}))).then((result) => {
  final_results.push(result)
}).catch((e) => {
  final_results.push(e)
}).then(() => {
  resolve(final_results)
});

其他推荐答案

您立即解决或拒绝pool.query()回调开始:

if(err){ reject(err);}resolve(results);

因此,除非查询失败,否则您永远不会通过apollofetch呼叫的结果解决,因为pool.query()结果已经解决了承诺.我想您缺少else块:

if( err ) {
  reject();
}
else {
  const promises = ...
}

ps:您可以尝试使用node.js'util.promisify()将pool.query()变成诺言,这样您就可以写一些类似的东西:query(...).then(results=>results.map(apolloFetch)而不是ahving来混合回调和承诺.

本文地址:https://www.itbaoku.cn/post/1938108.html

问题描述

I'm trying to use apolloFetch inside a Promise.all in my Node.js microservice but keep getting an error that the query is empty. The reason for using apolloFetch is to call another micro service and pass it an array of queries. Can someone give me some direction? My code is as follows:

   const uri = "dsc.xxx.yyyy.com/abc/def/graphql";
   const apolloFetch = CreateApolloFetch({uri});
  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);
                }
                //Below is the Promise.all function with the   
                //apolloFetch that calls another graphql endpoint
                //an array of queries
                Promise.all(promises.map(p => apolloFetch({p}))).then((result) => {
                    //this is the problem code^^^^^^^^^^^^^^^^^^^^^ 
                    resolve();
                    console.log("success!");
                }).catch((e) => {
                    FunctionLogError(29, "Error", e);
                });
            });
        });
    }
};
module.exports = {
    QryAllBooks,
    BookType
};

推荐答案

It looks like apolloFetch requires query - you are passing p

change

Promise.all( promises.map(p=>apolloFetch({p})) )

to

Promise.all( promises.map(query=>apolloFetch({query})) )

You also call resolve twice

To resolve all errors or success

const final_results = []
Promise.all(promises.map(query => apolloFetch({
  query,
}))).then((result) => {
  final_results.push(result)
}).catch((e) => {
  final_results.push(e)
}).then(() => {
  resolve(final_results)
});

其他推荐答案

You immediately resolve or rejects once the pool.query() callback starts:

if(err){ reject(err);}resolve(results);

So unless the query fails, you never resolve with the results from the apolloFetch calls, since the promise is already resolved with the pool.query() results. I guess you're missing an else block:

if( err ) {
  reject();
}
else {
  const promises = ...
}

PS: you can try using node.js' util.promisify() to turn pool.query() into a promise as well so you can just write something resembling: query(...).then(results=>results.map(apolloFetch) instead of ahving to mix callbacks and promises.