Home > Net >  How can I return a separate value along with the result of a promise?
How can I return a separate value along with the result of a promise?

Time:11-05

I am returning a promise, but I am trying to return a string AND a promise. Is there a way to link the two without having to return it from the promise?

for example if my input was

[
  {
    keepme:"abcd",
    sql:"select top(1) * from X"
  }
]

My goal is to return

[
  {
    keepme:"abcd",
    sql:"select top(1) * from X",
    resultOfPromise:[{columnA:1,columnB:2}]
  }
]

Here is my code so far. It returns the promise, but not the abcd value:

let qq=[{keepme:"abcd",sql:"select top(1) * from X"}]

async function myFunc(sql:string){
    return [{columnA:1,columnB:2}]
}

async function run(){
let prom=qq.map((qq) => myFunc(qq.sql));

    for (let p of await (Promise as any).allSettled(prom)) {
      console.log(p.value)
    }
}

run();

CodePudding user response:

You can return an object with the promise result as one of its properties:

const getDataWithInputs = async (keepme, ...input) => {
  let data = await getData(...input);
  return {
    data,
    input,
    keepme
  }
}

and when calling it:

let prom = qq.map((qq) => myFunc(qq.keepme, qq.sql));

Also you should always pad operators with spaces.

CodePudding user response:

You could make your map callback async and inject the promised value with await into a new object literal, which copies the other properties from qq:

let qq = [{keepme: "abcd", sql: "select top(1) * from X"}];

async function myFunc(sql) {
    return [{columnA: 1, columnB: 2}];
}

async function run(){
    let prom = qq.map(async (qq) => ({
        ...qq,
        resultOfPromise: await myFunc(qq.sql)
    }));

    for (let p of await Promise.allSettled(prom)) {
        console.log(p.value);
    }
}

run();

  • Related