noob_coder
noob_coder

Reputation: 55

Can I use then() when the previous block does not return a promise? I just want some async functions to run in a specific order

Suppose I have 2 async functions and I want them to run sequentially in the order. myGET() and then myPOST(). I have created functions and not chained the operations them with .then() blocks directly because for the reusability of that code. Is there more graceful way to run functions with asynchronous code in a sequence?

function myGET() {
  var str = null;
  // use fetch to get text for str
  // if there is some error, str will be null
  return str;
}

function myPOST(value) {
  var str = null;
  // use fetch to post the value and get the text for str
  // if there is some error, str will be null
  return str;
}

myGET()
.then( function(value) {
  if(value == null) return;
  var str = myPOST(value);
  console.log(str);
});

Upvotes: 0

Views: 53

Answers (1)

sergdenisov
sergdenisov

Reputation: 8572

You could try to use Promise.resolve():

Promise.resolve(myGET()).then((value) => {
  if (value == null) return;
  const str = myPOST(value);
  console.log(str);
});

Upvotes: 1

Related Questions