Promise

var contrived = { count: Math.floor(Math.random() * 10) + 1   }
console.log(contrived)

let myFirstPromise = new Promise((resolve, reject) => {
if (contrived.count > 0) {
    fetch("https://httpbin.org/ip")
    .then(function (res) { return res.json() })
    .then((json) => { Object.assign(contrived, json)
                      resolve(contrived) })
} else {
    console.log("here")
    resolve(contrived)
}
})

myFirstPromise.then(console.log)

Async / Await

const outerContrived = {
  count: Math.floor(Math.random() * 10) + 1,
}
console.log('Before', outerContrived)

const goget = async function(contrived) {
  console.log('in goget', contrived)

  if (contrived.count > 0) {
    const response = await fetch('https://httpbin.org/ip')
    const json = await response.json()
    Object.assign(contrived, json)
  } else {
    console.log(contrived.count)
  }
}

goget(outerContrived)

console.log('After', outerContrived)
Feedback

Powered by Vanilla PHP feedback form