Calling an async function when a constructor() is present - javascript

I have an async function that generates a new token if a user's token expires. I copied and pasted the async function code into this project and the class and constructor were already built.
I want to call the async function but I'm not sure how/where to do it, especially with the constructor function present. I can see how and where the other async functions are called (i.e. var _token = await sessionGet(_tokenName)), but since the async function I want to call is the outermost async function (if that makes sense) I'm not sure where I'd call it.
Here's what I know (correct me if I'm wrong):
I can't use await outside an async function
It's a bad practice to have a constructor function return a Promise
My async function has to be async or else it'll "break the flow" of the rest of the code---async is used multiple times throughout
export default class {
constructor() {
this.setTokenVar();
// other function calls
}
setTokenVar() {
async function permissionToCallAPI() { // -------- this is what I want to call
const _tokenName = "tokenSet",
_RestHost = "https://.../.../api";
async function sessionGet(key) {
let stringValue = window.sessionStorage.getItem(key);
if (stringValue != null) {
try {
const {
value,
expirationDateStr
} = JSON.parse(stringValue);
if (value && expirationDateStr) {
let expirationDate = new Date(expirationDateStr);
if (expirationDate <= new Date()) {
throw "Expired Token";
}
const isValid = await isAuthorized(value.value);
if (isValid) {
console.log("Valid Token");
return value;
} else {
throw "Expired Token";
}
} // if (value && expirDateStr)
} catch (e) {
console.log(e);
window.sessionStorage.removeItem(key);
}
}
return null;
}
async function isAuthorized(key) {
let ret = false;
await axios.post(_RestHost + "/User/GenerateToken", null, {
withCredentials: true,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json",
"Authorization": key
}
}).then(resp => {
ret = true;
})
.catch(err => {
console.log("Failed Authentication.");
});
return ret;
}
// add into session
function sessionSet(key, value, expirationInMin) {
if (!expirationInMin) {
expirationInMin = 59;
}
var expirationDate = new Date(
new Date().getTime() + 60000 * expirationInMin
);
var newValue = {
value: value,
expirationDateStr: expirationDate.toISOString()
};
window.sessionStorage.setItem(key, JSON.stringify(newValue));
}
var _token = await sessionGet(_tokenName);
if (_token == null) {
let request = axios
.get(_RestHost + "/User/GenerateToken", {
withCredentials: true
});
return request
.then(response => {
const authToken = response.data.AuthToken;
sessionSet(_tokenName, authToken);
return authToken;
})
.catch(err => {
throw err;
});
} else {
return _token;
}
} // permToCallAPI
} // setTokenVar()
}

Doing anything but setting variables in the constructor is considered an anti-pattern.
The simplest solution is to make the caller responsible for calling obj.setTokenVar() which could then be an async function.
Since the object's state may be inconsistent before that method is called, you could create a factory async function to guarantee that the object is fully initialized before letting callers use it.
export async createThing() {
const obj = new Thing();
await obj.setTokenVar();
return obj;
}
Side Note
async can be called from non async functions, but you cannot use await on it, you must use then on the Promise that all async functions return.
function doSomething() {
createThing().then(thing => console.log(thing))
}
function async doSomething() {
console.log(await createThing())
}

Related

async await not working in composable function vue 3

In my project I have a function for downloading the files. When click the button the function onDownload will be called:
import {useOnDownload} from "../../use/useOnDownload"
setup() {
...
const loading = ref(null)
onDownload = (id) => {
loading.value = id
await useOnDownload(id)
loading.value = null
}
return {loading, onDownload}
}
I refactored the code for api in a file useOnDownload.js call because the same code is used in another components as well.
export async function useOnDownload(id) {
// make api call to server with axios
}
What I did wrong? I need to wait for the function useOnDownload ... in order the loader to work.
Here is how to make async composable functions with async await syntax
export default function useOnDownload() {
const isLoading = ref(true);
const onDownload = async () => {
isLoading.value = true;
try {
const { data } = await axios.post('/api/download', {id: id},
{responseType: 'blob'})
// handle the response
} catch (error) {
console.log(error);
} finally {
isLoading.value = false;
}
};
// invoke the function
onDownload();
return { // return your reactive data here };
}
import useOnDownload from "../../use/useOnDownload"
// no await in setup script or function
const { reactiveDataReturned } = useOnDownload();
Read more here
onDownload must be async in order to use await within it
I managed to solved another way without async and await...
I passed the reference object loader to the function parameter (as optional) and handle from there...
export function useOnDownload(id, loader) {
if(loader !== undefined) {
loader.value = id
}
axios.post('/api/download', {id: id}, {
responseType: 'blob'
}).then(response => {
// handle the response
...
if(loader !== undefined) {
loader.value = null
}
}).catch(error => {
// handle the error
...
if(loader !== undefined) {
loader.value = null
}
})
}
You are using the await keyword in your onDownlaod function, but the function is not asynchronous. Here's how you should update it.
// next line important
onDownload = async(id) => {
loading.value = id
await useOnDownload(id)
loading.value = null
}

Repeat async function until true

I have an async function that checks for the status of an order (checkOrderStatus()). I would like to repeat this function until it returns either "FILLED" or "CANCELED", then use this return value in another function to decide to continue or stop the code. Every order goes through different status before being "FILLED" or "CANCELED", therefore the need to repeat the checkOrderStatus() function (it is an API call).
What I have now is this, to repeat the checkOrderStatus() function:
const watch = filter => {
return new Promise(callback => {
const interval = setInterval(async () => {
if (!(await filter())) return;
clearInterval(interval);
callback();
}, 1000);
});
};
const watchFill = (asset, orderId) => {
return watch(async () => {
const { status } = await checkOrderStatus(asset, orderId);
console.log(`Order status: ${status}`);
if (status === 'CANCELED') return false;
return status === 'FILLED';
});
};
I then call watchFill() from another function, where I would like to check its return value (true or false) and continue the code if true or stop it if false:
const sellOrder = async (asset, orderId) => {
try {
const orderIsFilled = await watchFill(asset, orderId);
if (orderIsFilled) {
//… Continue the code (status === 'FILLED'), calling other async functions …
}
else {
//… Stop the code
return false;
}
}
catch (err) {
console.error('Err sellIfFilled() :', err);
}
};
However, this does not work. I can see the status being updated in the terminal via the console.log in watchFill(), but it never stops and most importantly, the value in the orderIsFilled variable in sellOrder() does not get updated, whatever the value returned by watchFill() becomes.
How can I achieve the desired behavior?
watch never calls resolve (in the original code, this is misleadingly named callback()) with any value, so there's no way const orderIsFilled = await watchFill(asset, orderId); will populate orderIsFilled with anything but undefined.
If you save the result of await filter() in a variable and pass it to
callback as callback(result), your code seems like it should work.
That said, the code can be simplified by using a loop and writing a simple wait function. This way, you can return a value (more natural than figuring out how/when to call resolve), keep the new Promise pattern away from the logic and avoid dealing with setInterval and the bookkeeping that goes with that.
const wait = ms =>
new Promise(resolve => setTimeout(resolve, ms))
;
const watch = async (predicate, ms) => {
for (;; await wait(ms)) {
const result = await predicate();
if (result) {
return result;
}
}
};
/* mock the API for demonstration purposes */
const checkOrderStatus = (() => {
let calls = 0;
return async () => ({
status: ++calls === 3 ? "FILLED" : false
});
})();
const watchFill = (asset, orderId) =>
watch(async () => {
const {status} = await checkOrderStatus();
console.log(`Order status: ${status}`);
return status === "CANCELLED" ? false : status === "FILLED";
}, 1000)
;
const sellOrder = async () => {
try {
const orderIsFilled = await watchFill();
console.log("orderIsFilled:", orderIsFilled);
}
catch (err) {
console.error('Err sellIfFilled() :', err);
}
};
sellOrder();
You can use recursive functionality like this:
const checkOrderStatus = async () => {
// ... function does some work ...
await someOtherFunction() // you can use here the other async function as well
// ... function does some more work after returning from await ...
if(/* if status is FILLED or CANCELED */) {
// return true or false or some info about response for your needs
} else {
checkOrderStatus();
}
}
// this will response back when status will be FILLED or CANCELED
await checkOrderStatus();
The watch function clears the interval timer after the first call if filter resolves with false. setInterval doesn't wait for an async function to finish executing either so you'll have to create a loop yourself. Try this:
const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
const watch = async check => {
while (true) {
if (await check()) {
return;
}
await delay(1000);
}
};
Because watch only resolves when check succeeds, it is not possible to fail so you don't need to check for it (this might be a bug in your code):
const sellOrder = async (asset, orderId) => {
try {
await watchFill(asset, orderId);
//… Continue the code (status === 'FILLED'), calling other async functions …
}
catch (err) {
console.error('Err sellIfFilled() :', err);
}
};
p-wait-for contains an excellent implementation of this. You can use it like so:
import pWaitFor from 'p-wait-for';
const watchFill = (asset, orderId) => pWaitFor(async () => {
const { status } = await checkOrderStatus(asset, orderId);
console.log(`Order status: ${status}`);
if (status === 'CANCELED') return false;
return status === 'FILLED';
}, {
interval: 1000,
leadingCheck: false
});

How to use async function with key value pairs Google Chrome Extension?

Inside a function I have an async function which initializes the variables(defineVariables) by calling another async function called getLocalStorageValue that returns a promise. When the defineVariables function is done setting all the variables, it calls another function called response which alerts startTimeHour.value and endTimeHour.value. However the values are undefined. What should I do?
The Code:
chrome.webNavigation.onDOMContentLoaded.addListener(function() {
let startTimeHour;
let endTimeHour;
let startTimeMin;
let endTimeMin;
defineVariables();
async function defineVariables(){
startTimeHour = await getLocalStorageValue("startTimeHour");
endTimeHour = await getLocalStorageValue("endTimeHour");
startTimeMin = await getLocalStorageValue("startTimeMin");
endTimeMin = await getLocalStorageValue("endTimeMin");
response();
}
function response(){
if(startTimeHour != null && endTimeHour != null){
alert(startTimeHour)
alert(endTimeHour)
}else{
alert("could not get values")
}
chrome.tabs.query({active:true,currentWindow:true},(tabs)=>{
chrome.tabs.sendMessage(tabs[0].id,'execoverlay',(resp)=>{
console.log(resp.msg)
})
})
}
}, {url: [{urlMatches : 'https://mail.google.com/'}]});
async function getLocalStorageValue(key) {
return new Promise((resolve, reject) => {
try {
chrome.storage.sync.get(key, function (value) {
resolve(value);
})
}
catch (ex) {
reject(ex);
}
});
}
Try using
return response()
so it runs after all the variables have been set.

Axios requests with express, node, ejs

I am working on a site using Express.js, node.js, Axios, and ejs. I am making REST calls to a Oracle SQL REST services using Axios. I am having trouble working with Promises or Async/Await. I could use some guidance, if possible.
I have a repository layer to interface with the Oracle DB. For example:
dataaccess.js
const axios = require('axios');
exports.IsManufacturerCategory = function (categoryId) {
axios.get(`DB ADDRESS ${categoryId}`)
.then(response => {
console.error('GET IsManufacturerCategory categoryId = ' + categoryId);
console.error('Response = ' + JSON.stringify(response.data));
return (response.data);
})
.catch(rej => {
console.error('ERROR IsManufacturerCategory categoryId = ' + categoryId);
console.error('ERR = \n' + rej.data);
return (rej.data);
});
}
Which is called in my middleware. When I call var isManufacturerCat = exports.IsManufacturerCategory(categoryId); it is undefined. I am attempting to use the data retrieved from the Axios call to return a ejs view to my router, which I can provide if needed.
category.js
var isManufacturerCat = exports.IsManufacturerCategory(categoryId);
if (isManufacturerCat) {
var models = dataaccess.GetCategorySubCategories(categoryId);
return ("manufacturers", {
data: {
Canonical: cononical,
Category: category,
IsAManufacturerCategory: iAManufacturerCat,
Models: models
}
});
}
I am open to any advice in my project structure, usage of Promises, Async/Await, etc.
Thank you in advance.
EDIT
After working with some of the answers given, I have made some progress but I am having issues with layers of async calls. I end up getting into a spot where I need to await a call, but I am in a function that I am not able/do not want to do so (i.e. my router).
indexMiddleware.js
exports.getRedirectURL = async function (fullOrigionalpath) {
if (fullOrigionalpath.split('.').length == 1 || fullOrigionalpath.indexOf(".aspx") != -1) {
if (fullOrigionalpath.indexOf(".aspx") != -1) {
//some string stuff to get url
}
else if (fullOrigionalpath.indexOf("/solutions/") != -1) {
if (!fullOrigionalpath.match("/solutions/$")) {
if (fullOrigionalpath.indexOf("/t-") != -1) {
//some stuff
}
else {
var solPart = fullOrigionalpath.split("/solutions/");
solPart = solPart.filter(function (e) { return e });
if (solPart.length > 0) {
var solParts = solPart[solPart.length - 1].split("/");
solParts = solParts.filter(function (e) { return e });
if (solParts.length == 1) {
waitForRespose = true;
const isASolutionCategory = await dataaccess.isASolutionCategory(solParts[0]); // returns void
if (isASolutionCategory != undefined && isASolutionCategory.length > 0 && isASolutionCategory[0].Count == 1) {
// set redirecturl
}
}
else {
redirecturl = "/solutions/solutiontemplate";
}
}
}
}
}
else if (URL STUFF) {
// finally if none of the above fit into url condition then verify current url with Category URL or product url into database and if that matches then redirect to proper internal URL
if (fullOrigionalpath.lastIndexOf('/') == (fullOrigionalpath.length - 1)) {
fullOrigionalpath = fullOrigionalpath.substring(0, fullOrigionalpath.lastIndexOf('/'));
}
waitForRespose = true;
const originalURL = await exports.getOriginalUrl(fullOrigionalpath); //returns string
redirecturl = originalURL;
return redirecturl;
}
}
if (!waitForRespose) {
return redirecturl;
}
}
exports.getOriginalUrl = async function (friendlyUrl) {
var originalUrl = '';
var urlParts = friendlyUrl.split('/');
urlParts = urlParts.filter(function (e) { return e });
if (urlParts.length > 0) {
var skuID = urlParts[urlParts.length - 1];
const parts = await dataaccess.getFriendlyUrlParts(skuID); //returns void
console.log("Inside GetOriginalUrl (index.js middleware) FriendlyUrlParts: " + parts);//undefined
if (parts != undefined && parts != null && parts.length > 0) {
//some stuff
}
else {
// verify whether it's category URL then return the category local URL
console.log('Getting CategoryLocalUrl');
const categoryLocalUrl = await dataaccess.getCategoryLocalUrl(friendlyUrl); // returns void
console.log('CategoryLocalUrl Gotten ' + JSON.stringify(categoryLocalUrl)); //undefined
if (categoryLocalUrl != undefined && categoryLocalUrl.length > 0) {
//set originalUrl
return originalUrl;
}
}
}
else { return ''; }
}
index.js router
router.use(function (req, res, next) {
//bunch of stuff
index.getRedirectURL(url)
.then(res => {
req.url = res;
})
.catch(error => {
console.error(error);
})
.finally(final => {
next();
});
}
I am getting undefined in my console.logs after the awaits. I'm not really sure what I'm doing I guess.
Let's start with dataaccess.js. Basically, you're exporting a function that's doing async work, but the function isn't async. Most people want to be able to utilize async/await, so rather than have IsManufacturerCategory accept a callback function, it would better to have the function return a promise. The easiest way to do that is to make the function an async function. Async functions return promises which are resolved/rejected more easily than by returning an explicit promise. Here's how that could be rewritten:
const axios = require('axios');
exports.IsManufacturerCategory = async function (categoryId) {
try {
const response = await axios.get(`DB ADDRESS ${categoryId}`);
console.log('GET IsManufacturerCategory categoryId = ' + categoryId);
console.log('Response = ' + JSON.stringify(response.data));
} catch (err) {
console.error('ERROR IsManufacturerCategory categoryId = ' + categoryId);
console.error('ERR = \n' + rej.data);
throw err;
}
}
Note that I'm using console.error only for errors. Because you wanted to log some error related details, I used a try/catch statement. If you didn't care about doing that, the function could be simplified to this:
const axios = require('axios');
exports.IsManufacturerCategory = async function (categoryId) {
const response = await axios.get(`DB ADDRESS ${categoryId}`);
console.log('GET IsManufacturerCategory categoryId = ' + categoryId);
console.log('Response = ' + JSON.stringify(response.data));
}
This is because async functions automatically swallow errors and treat them as rejections - so the promise returned by IsManufacturerCategory would be rejected. Similarly, when an async function returns a value, the promise is resolved with the value returned.
Moving on to category.js... This looks strange because you're accessing IsManufacturerCategory from the exports of that module when I think you mean to access it from the import of the dataaccess module, right?
Inside this function, you should put any async work in an async function so that you can use await with function that return promises. Here's how it could be rewritten:
const dataaccess = require('dataccess.js');
async function validateManufacturerCat(categoryId) {
const isManufacturerCat = await dataaccess.IsManufacturerCategory(categoryId);
if (isManufacturerCat) {
const models = await dataaccess.GetCategorySubCategories(categoryId);
return ({
manufacturers: {
data: {
Canonical: cononical,
Category: category,
IsAManufacturerCategory: iAManufacturerCat,
Models: models
}
}
});
}
}
validateManufacturerCat(categoryId)
.then(res => {
console.log(res);
})
.catch(err => {
console.error(err);
});
A couple notes:
I changed the return value in the if statement to be a single value. You should try to always return a single value when working with promises and async/await (since you can only resolve/return one value).
I see lots of functions starting with capital letters. There's a convention in JavaScript where functions with capital letters are constructor functions (meant to be invoked with the new keyword).
Here is a working example. Note that you need a callback function to get the data when it is available from the promise
//client.js
const axios = require("axios")
exports.IsManufacturerCategory = function (url, callback) {
axios.get(url)
.then(response=>
{
callback(response.data);
})
.catch(error=>{
callback( error);
})
};
//app.js
const client = require('./client');
function process(data) {
console.log(data)
}
client.IsManufacturerCategory("http://localhost:3000/persons",process);
documentation

Trouble with async await and non async functions

I'm trying deal with a library that using async functions and am a little lost. I want to call a function that returns a string but am getting tripped up. Here's what I have so far. The ZeroEx library functions all seem to use async /await so my understanding is that I can only call them from another async method. But won't this just cause a chain reaction meaning every method needs to be async? Or am I missing something?
function main() {
var broker = zmq.socket('router');
broker.bindSync('tcp://*:5671');
broker.on('message', function () {
var args = Array.apply(null, arguments)
, identity = args[0]
, message = args[1].toString('utf8');
if(message === 'TopOfBook') {
broker.send([identity, '', getTopOfBook()]);
}
//broker.send([identity, '', 'TEST']);
//console.log('test sent');
})
}
async function getTopOfBook() {
var result: string = 'test getTopOfBook';
const EXCHANGE_ADDRESS = await zeroEx.exchange.getContractAddress();
const wethTokenInfo = await zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync('WETH');
const zrxTokenInfo = await zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync('ZRX');
if (wethTokenInfo === undefined || zrxTokenInfo === undefined) {
throw new Error('could not find token info');
}
const WETH_ADDRESS = wethTokenInfo.address;
const ZRX_ADDRESS = zrxTokenInfo.address;
return result;
}
main();
The function getTopOfBook() isn't returning anything back to the main() function so the result is never being sent by the broker. The commented out broker.send() with 'TEST' is working fine however. Thanks for looking.
EDIT:
I tried to make the main method async so I could use await but it's giving an error that I can only use await in an async function. Could the broker.on() call be causing this?
const main = async () => {
try{
var broker = zmq.socket('router');
broker.bindSync('tcp://*:5671');
broker.on('message', function () {
var args = Array.apply(null, arguments)
, identity = args[0]
, message = args[1].toString('utf8');
console.log(message);
if(message === 'TopOfBook') {
>> var test = await getTopOfBook();
console.log('in top of book test');
broker.send([identity, '', test]);
}
//broker.send([identity, '', 'TEST']);
//console.log('test sent');
})
} catch (err) {
console.log(err);
}
}
EDIT 2:
My current working code, thanks everyone that had advice/solutions! I obviously have to fill out the getTopOfBook() function to return an actual result still. If you have more recommendations send them my way. I'm trying to build out a backend that will get data from a geth rpc and send it to a C# GUI front end.
var main = function() {
try{
var broker = zmq.socket('router');
broker.bindSync('tcp://*:5672');
broker.on('message', function () {
var args = Array.apply(null, arguments)
, identity = args[0]
, message = args[1].toString('utf8');
if(message === 'TopOfBook') {
getTopOfBook().then((result) => {
broker.send([identity, '', result])
});
}
})
} catch (err) {
console.log(err);
}
}
async function getTopOfBook() {
var result: string = 'test getTopOfBook';
const EXCHANGE_ADDRESS = await zeroEx.exchange.getContractAddress();
const wethTokenInfo = await zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync('WETH');
const zrxTokenInfo = await zeroEx.tokenRegistry.getTokenBySymbolIfExistsAsync('ZRX');
if (wethTokenInfo === undefined || zrxTokenInfo === undefined) {
throw new Error('could not find token info');
}
const WETH_ADDRESS = wethTokenInfo.address;
const ZRX_ADDRESS = zrxTokenInfo.address;
return result;
}
main();
The callback function needs to be async
broker.on('message', async function () {
var args = Array.apply(null, arguments)
, identity = args[0]
, message = args[1].toString('utf8');
if(message === 'TopOfBook') {
var test = await getTopOfBook();
broker.send([identity, '', test]);
}
//broker.send([identity, '', 'TEST']);
//console.log('test sent');
})
You are missing the point that async functions are just a way to write the code. Every async function what actually does is generate a promise. That is why you can await any promise and you can interact with any library that uses async without the need of using async functions yourself.
When you call an async function it should return a promise (which happens automatically on async function). A promise is nothing but an object with a then method. Such method accepts a callback, where you can handle the rest of the logic.
function main() {
var broker = zmq.socket('router');
broker.bindSync('tcp://*:5671');
broker.on('message', function () {
var args = Array.apply(null, arguments)
, identity = args[0]
, message = args[1].toString('utf8');
if(message === 'TopOfBook') {
return getTopOfBook().then( result =>
broker.send([identity, '', result])
) // If the broker also returns a promise, you can continue the flow here
.then(()=> console.log('test sent'))
}
})
}
Personally I don't like async await at all because the involve too much magic and make people to forget about the actual nature of promises and asynchronous code.
Also when dealing with promises you should always remember to return any promise you could call/generate so outer code can continue the chain and handle error messages.
Your function getTopOfBook returns a Promise, so you need to use the function then
Call that function as follow:
getTopOfBook().then((result) => {
console.log("Result:" + result);
});
Look at this code snippet
let sleep = (fn) => {
setTimeout(fn, 1000);
};
let getContractAddress = function(cb) {
return new Promise((r) => sleep(() => {
r('getContractAddress')
}));
};
let getTokenBySymbolIfExistsAsync = function(str) {
return new Promise((r) => sleep(() => {
r({
address: 'getTokenBySymbolIfExistsAsync: ' + str
})
}));
};
let WETH_ADDRESS = '';
let ZRX_ADDRESS = '';
let EXCHANGE_ADDRESS = '';
async function getTopOfBook() {
var result = 'test getTopOfBook';
const EXCHANGE_ADDRESS = await getContractAddress();
const wethTokenInfo = await getTokenBySymbolIfExistsAsync('WETH');
const zrxTokenInfo = await getTokenBySymbolIfExistsAsync('ZRX');
if (wethTokenInfo === undefined || zrxTokenInfo === undefined) {
return Promise.reject(new Error('could not find token info'));
}
const WETH_ADDRESS = wethTokenInfo.address;
const ZRX_ADDRESS = zrxTokenInfo.address;
console.log(WETH_ADDRESS);
console.log(ZRX_ADDRESS);
console.log(EXCHANGE_ADDRESS);
return result;
}
var main = function() {
console.log('Waiting response...');
getTopOfBook().then((result) => {
console.log("Result:" + result);
console.log('DONE!');
}).catch((error) => {
console.log(error);
});
};
main();
.as-console-wrapper {
max-height: 100% !important
}
If you want to throw an error use the function Promise.reject()
Along with that call, you need either to pass the reject function or call the catch function.
In this example, we're passing the reject function:
(error) => {
console.log(error);
}
If you don't pass the reject function, you need to call the catch function in order to handle the thrown error.
let sleep = (fn) => {
setTimeout(fn, 1000);
};
let getContractAddress = function(cb) {
return new Promise((r) => sleep(() => {
r('getContractAddress')
}));
};
let getTokenBySymbolIfExistsAsync = function(str) {
return new Promise((r) => sleep(() => {
r()
}));
};
let WETH_ADDRESS = '';
let ZRX_ADDRESS = '';
let EXCHANGE_ADDRESS = '';
async function getTopOfBook() {
var result = 'test getTopOfBook';
const EXCHANGE_ADDRESS = await getContractAddress();
const wethTokenInfo = await getTokenBySymbolIfExistsAsync('WETH');
const zrxTokenInfo = await getTokenBySymbolIfExistsAsync('ZRX');
if (wethTokenInfo === undefined || zrxTokenInfo === undefined) {
return Promise.reject('Could not find token info');
}
const WETH_ADDRESS = wethTokenInfo.address;
const ZRX_ADDRESS = zrxTokenInfo.address;
console.log(WETH_ADDRESS);
console.log(ZRX_ADDRESS);
console.log(EXCHANGE_ADDRESS);
return result;
}
var main = function() {
console.log('Waiting response...');
getTopOfBook().then((result) => {
console.log("Result:" + result);
console.log('DONE!');
}, (error) => {
console.log(error);
}).catch((error) => {
console.log(error); // This line will be called if reject function is missing.
});
};
main();
.as-console-wrapper {
max-height: 100% !important
}
Resource
Promise.prototype.then()
Promise.reject()
Async function
When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.

Categories

Resources